package Demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo99 {
    public static void main (String[] args)  {
        tickets t=new tickets ();
        new Thread (()->{
            for (int i = 0; i <10 ; i++) {
                t.printA ();
            }
        },"A").start ();
        new Thread (()->{
            for (int i = 0; i <10 ; i++) {
                t.printB ();
            }
        },"B").start ();
        new Thread (()->{
            for (int i = 0; i <10 ; i++) {
                t.printC ();
            }
        },"C").start ();
    }
}

class tickets {
    Lock lock = new ReentrantLock ();
    Condition condition1 = lock.newCondition ();
    Condition condition2 = lock.newCondition ();
    Condition condition3 = lock.newCondition ();
    int number=1;
    public void printA () {
        lock.lock ();
        try {
            try {
                while (number!=1){
                    condition1.await ();
                }
                System.out.println (Thread.currentThread ().getName ()+"=>AAAAA");
            } catch (InterruptedException e) {
                e.printStackTrace ();
            } finally {
                number=2;
                condition2.signal ();
            }
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            lock.unlock ();
        }
    }
    public void printB(){
        lock.lock ();
        try {
            try {
                while (number!=2){
                    condition2.await ();
                }
                System.out.println (Thread.currentThread ().getName ()+"=>BBBBB");
            } catch (InterruptedException e) {
                e.printStackTrace ();
            } finally {
                number=3;
                condition3.signal ();
            }
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            lock.unlock ();
        }
    }
    public void printC(){
        lock.lock ();
        try {
            try {
                while (number!=3){
                    condition3.await ();
                }
                System.out.println (Thread.currentThread ().getName ()+"=>CCCCC");
            } catch (InterruptedException e) {
                e.printStackTrace ();
            } finally {
                number=1;
                condition1.signal ();
            }
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            lock.unlock ();
        }
    }
}
